# -*- coding: utf-8 -*-
'''
Created on 2013-4-3

@author: chenkaode@baidu.com
'''

from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4 import uic
from PyQt4 import QtCore, QtGui
import os,sys
import ui_main
from PathSelectDlg import *
import subprocess

class MainDlg(QDialog,ui_main.Ui_Dialog):
    def __init__(self,parent=None):
        super(MainDlg,self).__init__(parent)
        self.setupUi(self)
        self.child = None
        self.child = PathSelectDlg();
        self.connect(self.selectVersionButton,SIGNAL("clicked()"),self.slotChild)
        self.connect(self.flashbutton, SIGNAL("clicked()"),self.flashRom)
        
    def slotChild(self):
        self.child.show();
        
    def flashRom(self):
        print self.child.imgPath
        bootImg = self.child.imgPath + os.sep + "boot.img"
        systemImg = self.child.imgPath + os.sep + "system.img"
        userdataImg = self.child.imgPath + os.sep + "userdata.img"
        if not os.path.exists(bootImg) or not os.path.exists(systemImg) or not os.path.exists(userdataImg):
            print "not exists"
            sys.exit()
        self.flashProgressBar.setMinimum(0)
        self.flashProgressBar.setMaximum(10)
#         subp = subprocess.Popen("adb reboot-bootloader")
        os.system("adb reboot-bootloader")
#         subp.wait()
        QThread.msleep(1000)
#         subp = subprocess.Popen("fastboot devices",stdout=subprocess.PIPE)
#         out = subp.stdout.read()
#         if out == '':
#             sys.exit
#         else:
#             print out
#         subp.wait()
        QThread.msleep(1000)
        self.flashProgressBar.setValue(1)
        
        bootImg = str(bootImg)
        bootImg = bootImg.replace("\\", "\\\\")
        cmd = "fastboot flash boot " + bootImg
        print cmd
#         subp = subprocess.Popen(cmd)
#         subp.wait()
        os.system(cmd)
        self.flashProgressBar.setValue(3)
        QThread.msleep(2000)
        
        systemImg = str(systemImg)
        systemImg = systemImg.replace("\\", "\\\\")
        cmd = "fastboot flash system " + systemImg
        print cmd
        os.system(cmd)
#         subp = subprocess.Popen(cmd)
#         subp.wait()
        self.flashProgressBar.setValue(7)
        QThread.msleep(2000)
        
        userdataImg = str(userdataImg)
        userdataImg = userdataImg.replace("\\", "\\\\")
        cmd = "fastboot flash userdata " + userdataImg
        print cmd
        os.system(cmd)
#         subp = subprocess.Popen(cmd)
#         subp.wait()
        QThread.msleep(2000)
        self.flashProgressBar.setValue(10)